package com.controller;

import com.bean.Goods;
import com.bean.Msg;
import com.bean.Orders;
import com.bean.User;
import com.service.IGoodsService;
import com.service.IOrderService;
import com.service.ISeckillService;
import com.service.IUserService;
import com.shiro.token.JWTToken;
import com.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author arthorn
 * @create 2022-06-23-0:14
 */

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ISeckillService iSeckillService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IUserService iUserService;





    /**
     * 获取下单商品信息 然后生成订单
     * @param
     * @param totalprice
     * @return
     * @throws Exception
     */
    @PostMapping("/{goodsName}/{totalprice}/{goodsPrice}")
    public Msg getOrderMsg(@PathVariable("goodsName") String goodsName, @PathVariable Integer totalprice, @PathVariable Integer goodsPrice
            ,@RequestHeader("x-access-token") String jwt)throws Exception{
        //把jwt转化为Token，因为已经走了jwt认证了不需要判空和校验
        JWTToken jwtToken = new JWTToken(jwt);
        //解析jwt查找到user对象
        String email = jwtToken.getEmail();
        User user = iUserService.findByEmail(email);
        Goods goodsByName = goodsService.getGoodsByName(goodsName);
        Integer stock = goodsByName.getGoodsStock();
        Integer disStock=totalprice/goodsPrice;
        Orders orders=new Orders();
        orders.setOuId(user.getUserId());
        orders.setOrderStatus(1);
        orders.setOrderPrice(totalprice);
        orderService.createOrders(orders);
        //给中间表orders_goods插入数据
        iSeckillService.addorders_goods(orders.getOrderId(), goodsByName.getGoodsId());
        //给中间表seckill_order
        //商品库存-1
        goodsByName.setGoodsStock(stock-disStock);
        //更新库存
        goodsService.updateGoods(goodsByName);
        return Msg.success().add("result","订单创建成功");
    }

}
